package deviceMng

import (
	"autotestservice/testservices/internal/types"
	"encoding/json"
	"gitee.com/jmdvirus/jkgo/jk/jklog"
	"math/rand"
	"strconv"
	"time"
)

type DeviceOptionTestCmd struct {
	Timestamp   int64
	Cmd         string
	Transaction string
	PreResult   string
}

type DeviceOption struct {
	ConnectStyle string
	Addr         string
	Port         int
	Id           int64
}

func NewDeviceOption(style, addr string, port int) *DeviceOption {
	do := &DeviceOption{
		ConnectStyle: style,
		Addr:         addr,
		Port:         port,
	}
	rand.Seed(time.Now().UnixNano())
	do.Id = rand.Int63n(1000000) + 100000
	do.Id = time.Now().Unix()*1000000 + do.Id
	return do
}

func (do *DeviceOption) generateUrl(post string) string {
	return "http://" + do.Addr + ":" + strconv.Itoa(do.Port) + post
}

func (do *DeviceOption) GetId() int64 {
	return do.Id
}

func (do *DeviceOption) Connect(cmd DeviceOptionTestCmd) (types.Response, error) {
	res := types.Response{
		Code: 1,
	}
	if cmd.Cmd == "start" {
		jklog.L().Infoln("start test")
		data, _ := json.Marshal(cmd)
		rr, err := NewDeviceOptionHttp(do.generateUrl("/autotest/start")).Post(string(data))
		json.Unmarshal([]byte(rr), &res)
		return res, err
	}
	return res, nil
}

func (do *DeviceOption) Disconnect(cmd DeviceOptionTestCmd) error {
	if cmd.Cmd == "stop" {
		jklog.L().Infoln("stop test")
		_, err := NewDeviceOptionHttp(do.generateUrl("/autotest/stop")).Post(string(""))
		return err
	}
	return nil
}

func (do *DeviceOption) Test(cmd DeviceOptionTestCmd) (string, error) {
	// 发送 http 请求
	if do.ConnectStyle == "http" {
		data, _ := json.Marshal(cmd)
		return NewDeviceOptionHttp(do.generateUrl("/autotest/test")).Post(string(data))
	}

	return "", nil
}
